import axios from 'axios';
import router from '../router'
import Vue from 'vue';


axios.defaults.baseURL = "/api"
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true;



//http request 拦截器
axios.interceptors.request.use(
  config => {
    // const token = Cookies.get('sid');  
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type': 'application/json; charset=UTF-8;'
    }
    // if(token){
    //   config.params = {'token':token} 
    // }  
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.error == 401) {
      router.push({
        path: "/login",
        querry: {
          redirect: router.currentRoute.fullPath
        } //从哪个页面跳转
      })

      Vue.prototype.$message({
        message: '您的身份过期，请重新登录',
        type: 'warning'
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
        params: params
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


export function getStatus(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
        params: params
      })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function remove(url, data_t = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {
        data: data_t
      })
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}
